﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace Kokomo
{
	public class DelegatedCommand : ICommand
	{
		private Action<object> action;
		private Func<object, bool> canExecute;

		private static Action<object> CreateParameterlessThunk(Action action)
		{
			if (action == null) throw new ArgumentNullException("action");

			return (o) => action();
		}

		private static Func<object, bool> CreateParameterlessThunk(Func<bool> canExecute)
		{
			if (canExecute == null) throw new ArgumentNullException("canExecute");

			return (o) => canExecute();
		}

		public DelegatedCommand(
			Action action,
			Func<bool> canExecute = null,
			EventHandler canExecuteChanged = null
			) :
			this(
				CreateParameterlessThunk(action),
				((canExecute == null) ? null : CreateParameterlessThunk(canExecute)),
				canExecuteChanged
			)
		{ }
		public DelegatedCommand(
			Action<object> action,
			Func<object, bool> canExecute = null,
			EventHandler canExecuteChanged = null
			)
		{
			if (action == null) throw new ArgumentNullException("action");

			this.action = action;
			this.canExecute = canExecute;
		}

		public bool CanExecute(object parameter)
		{
			return (this.canExecute == null) || this.canExecute(parameter);
		}

		public event EventHandler CanExecuteChanged
		{
			add { CommandManager.RequerySuggested += value; }
			remove { CommandManager.RequerySuggested -= value; }
		}

		public void Execute(object parameter)
		{
			this.action(parameter);
		}
	}
}
